<?php
namespace app\admin\addons;
use app\admin\model\traits\TablHandle;
use maowenke\mysql\Restore;

class Addons
{
    /**安装插件
     * @param string $app
     * @return array|bool
     */
    public static function InstallAddonss(string $app=''){
        $filePath = root_path().'addons'.DIRECTORY_SEPARATOR.$app.DIRECTORY_SEPARATOR.'info.ini';
        $info = parse_ini_file($filePath);
        if($info['state']==1){
            return [false,'插件已安装'];
        }
        $appPath = root_path().'addons'.DIRECTORY_SEPARATOR.$app.DIRECTORY_SEPARATOR.'app';
        $appDir = root_path().'app';
        $bool = FieldHand::moveDir($appPath,$appDir,false);//移动后端文件
        if(!$bool){
            return [false,'移动文件失败'];
        }
        $publicPath = root_path().'addons'.DIRECTORY_SEPARATOR.$app.DIRECTORY_SEPARATOR.'public';
        $publicDir = root_path().'public';
        $bool = FieldHand::moveDir($publicPath,$publicDir,false);//移动静态文件
        if(!$bool){
            return [false,'移动文件失败'];
        }
        $obj = app('addons\myces\Plugin');
        if(method_exists($obj,'install')){
            $obj->install();
        }
        $mysqlPath = root_path().'addons'.DIRECTORY_SEPARATOR.$app.DIRECTORY_SEPARATOR.'install.sql';
        if(is_file($mysqlPath)){
            $config = getDataBaseConfig();
            $database = [
                'username' => $config['username'],
                'password' =>$config['password'],
                'host' => $config['hostname'].':'.$config['hostport'],
                'database' => $config['database'],
                'prefix' => $config['prefix'],
            ];
            $back_tool = new Restore($database);
            $bool = $back_tool->restore($mysqlPath);
            if(!$bool){
                return [false,'安装sql文件失败'];
            }
            $models = self::handStr(file_get_contents($mysqlPath),'CREATE TABLE `','` (','__PREFIX__');
            foreach ($models as $value){
                TablHandle::updatetable($value,'','mysql','',$app);
            }
        }


        $configPath = root_path().'addons'.DIRECTORY_SEPARATOR.$app.DIRECTORY_SEPARATOR.'info.ini';//修改配置文件
        $config = parse_ini_file($configPath);
        $config['state'] = 1;
        FieldHand::setIniConfig($configPath,$config);
        return [true,'安装成功'];
    }
    protected static function handStr($str,$start,$end,$rep=''){
        $str_array = explode($start,$str);
        $newarray = [];
        foreach ($str_array as $value){
            if(mb_strpos($value,$end)!==false){
                $array = explode($end,$value);
                if(isset($array[0])){
                    $array[0] = str_replace($rep,'',$array[0]);
                    $newarray[] = $array[0];
                }

            }
        }
        return $newarray;
    }
}